/*********************************************************************************
    This software is created under the term GNU General Public License.
    You should have received a copy of the GNU General Public License.
    If not, write to the Free Software Foundation, 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

critical:
    encapsulation critical section over different OSes

author: xiangyun.kong(lo-sor@hotmail.com)
create: 2-26-2011

changes:

**********************************************************************************/
#include <critical.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#if defined( _WINDOWS )

int init_critical( critical *cs )
{
	InitializeCriticalSection( cs );
	return 0;
}

void enter_critical( critical *cs )
{
	EnterCriticalSection( cs );
}

int try_enter_critical( critical *cs )
{
	if( TryEnterCriticalSection( cs ) )
		return 0;
	else
		return -1;
}

void leave_critical( critical *cs )
{
	LeaveCriticalSection( cs );
}

int destroy_critical( critical *cs )
{
	DeleteCriticalSection( cs );
	return 0;
}

#elif defined( LINUX )

int init_critical( critical *cs )
{
    if( cs == NULL )
    {
        cs = (critical *)malloc( sizeof(critical) );
        assert( cs != NULL );
    }

	return pthread_mutex_init( cs, NULL );
}

void enter_critical( critical *cs )
{
	pthread_mutex_lock( cs );
}

int try_enter_critical( critical *cs )
{
	return pthread_mutex_trylock( cs );
}

void leave_critical( critical *cs )
{
	pthread_mutex_unlock( cs );
}

int destroy_critical( critical *cs )
{
	return pthread_mutex_destroy( cs );
}

#else	// we give a empty implement for other os

int init_critical( critical *cs )
{
	return -1;
}

void enter_critical( critical *cs )
{
}

int try_enter_critical( critical *cs )
{
	return -1;
}

void leave_critical( critical *cs )
{
}

int destroy_critical( critical *cs )
{
	return -1;
}

#endif
